/**
 * 数据库操作辅助工具
 * 封装了对各集合的常用操作，包括用户、咨询申请、测评结果等数据的增删改查
 * 提供统一的接口简化数据库操作，增强代码可维护性
 */

// 初始化数据库连接
const db = wx.cloud.database();

//-------------------
// 集合引用定义
//-------------------

// 用户集合操作
const userCollection = db.collection('users');

// 心理咨询申请集合操作
const consultationRequestCollection = db.collection('consultation_requests');

// 心理测评结果集合操作
const evaluationResultCollection = db.collection('evaluation_results');

// 班级集合操作
const classCollection = db.collection('classes');

// 心理量表集合操作
const psychologicalScaleCollection = db.collection('psychological_scales');

// 预约时间段集合操作
const timeSlotCollection = db.collection('time_slots');

// 干预记录集合操作
const interventionRecordCollection = db.collection('intervention_records');

//-------------------
// 用户相关操作
//-------------------

// 获取用户信息
const getUserInfo = async (openid) => {
  try {
    console.log('dbHelper.getUserInfo - 开始查询用户, openid:', openid);
    
    const result = await userCollection.where({
      openid: openid
    }).get();
    
    console.log('dbHelper.getUserInfo - 查询结果:', result);
    console.log('dbHelper.getUserInfo - 查询到的数据条数:', result.data.length);
    
    if (result.data.length > 0) {
      const userData = result.data[0];
      console.log('dbHelper.getUserInfo - 返回用户数据:', userData);
      console.log('dbHelper.getUserInfo - 用户角色:', userData.role);
      console.log('dbHelper.getUserInfo - OpenID属性:', userData.openid);
      return userData;
    } else {
      console.log('dbHelper.getUserInfo - 未找到用户');
      return null;
    }
  } catch (error) {
    console.error('dbHelper.getUserInfo - 获取用户信息失败', error);
    console.error('dbHelper.getUserInfo - 错误详情:', error.message);
    return null;
  }
};

// 通过用户名和密码获取用户信息
const getUserInfoByUsernameAndPassword = async (username, password) => {
  try {
    console.log('dbHelper.getUserInfoByUsernameAndPassword - 开始查询用户, username:', username);
    
    const result = await userCollection.where({
      username: username,
      password: password
    }).get();
    
    console.log('dbHelper.getUserInfoByUsernameAndPassword - 查询结果:', result);
    console.log('dbHelper.getUserInfoByUsernameAndPassword - 查询到的数据条数:', result.data.length);
    
    if (result.data.length > 0) {
      const userData = result.data[0];
      console.log('dbHelper.getUserInfoByUsernameAndPassword - 返回用户数据:', userData);
      console.log('dbHelper.getUserInfoByUsernameAndPassword - 用户角色:', userData.role);
      return userData;
    } else {
      console.log('dbHelper.getUserInfoByUsernameAndPassword - 未找到用户');
      return null;
    }
  } catch (error) {
    console.error('dbHelper.getUserInfoByUsernameAndPassword - 获取用户信息失败', error);
    console.error('dbHelper.getUserInfoByUsernameAndPassword - 错误详情:', error.message);
    return null;
  }
};

// 通过用户名查询用户
const getUserInfoByUsername = async (username) => {
  try {
    console.log('dbHelper.getUserInfoByUsername - 开始查询用户, username:', username);
    
    const result = await userCollection.where({
      username: username
    }).get();
    
    console.log('dbHelper.getUserInfoByUsername - 查询结果:', result);
    console.log('dbHelper.getUserInfoByUsername - 查询到的数据条数:', result.data.length);
    
    if (result.data.length > 0) {
      const userData = result.data[0];
      console.log('dbHelper.getUserInfoByUsername - 返回用户数据:', userData);
      return userData;
    } else {
      console.log('dbHelper.getUserInfoByUsername - 未找到用户');
      return null;
    }
  } catch (error) {
    console.error('dbHelper.getUserInfoByUsername - 获取用户信息失败', error);
    console.error('dbHelper.getUserInfoByUsername - 错误详情:', error.message);
    return null;
  }
};

// 创建用户
const createUser = async (userData) => {
  try {
    const result = await userCollection.add({
      data: {
        ...userData,
        createTime: db.serverDate(),
        updateTime: db.serverDate()
      }
    });
    return result._id;
  } catch (error) {
    console.error('创建用户失败', error);
    return null;
  }
};

// 更新用户信息
const updateUser = async (openid, userData) => {
  try {
    const result = await userCollection.where({
      openid: openid
    }).update({
      data: {
        ...userData,
        updateTime: db.serverDate()
      }
    });
    return result;
  } catch (error) {
    console.error('更新用户信息失败', error);
    return null;
  }
};

//-------------------
// 咨询申请相关操作
//-------------------

// 创建心理咨询申请
const createConsultationRequest = async (requestData) => {
  try {
    const result = await consultationRequestCollection.add({
      data: {
        ...requestData,
        status: 'pending', // 默认状态为待审批
        createTime: db.serverDate(),
        updateTime: db.serverDate()
      }
    });
    return result._id;
  } catch (error) {
    console.error('创建心理咨询申请失败', error);
    return null;
  }
};

// 获取学生的所有咨询申请
const getStudentConsultationRequests = async (studentId) => {
  try {
    const result = await consultationRequestCollection.where({
      studentId: studentId
    }).orderBy('createTime', 'desc').get();
    return result.data;
  } catch (error) {
    console.error('获取学生咨询申请失败', error);
    return [];
  }
};

// 获取待审批的咨询申请（老师用）
const getPendingConsultationRequests = async () => {
  try {
    console.log('dbHelper.getPendingConsultationRequests - 开始查询待审批申请');
    
    const result = await consultationRequestCollection.where({
      status: 'pending'
    }).orderBy('createTime', 'desc').get();
    
    console.log('dbHelper.getPendingConsultationRequests - 查询结果:', result);
    console.log('dbHelper.getPendingConsultationRequests - 待审批申请数量:', result.data.length);
    
    if (result.data.length > 0) {
      const sample = result.data[0];
      console.log('dbHelper.getPendingConsultationRequests - 第一条申请示例:', sample);
      console.log('dbHelper.getPendingConsultationRequests - status值:', sample.status);
    }
    
    return result.data;
  } catch (error) {
    console.error('dbHelper.getPendingConsultationRequests - 获取待审批咨询申请失败', error);
    console.error('dbHelper.getPendingConsultationRequests - 错误详情:', error.message);
    return [];
  }
};

// 更新咨询申请状态
const updateConsultationRequestStatus = async (requestId, teacherId, status, rejectReason = '') => {
  try {
    const data = {
      status,
      teacherId,
      updateTime: db.serverDate()
    };
    
    if (status === 'rejected' && rejectReason) {
      data.rejectReason = rejectReason;
    }
    
    const result = await consultationRequestCollection.doc(requestId).update({
      data
    });
    return result;
  } catch (error) {
    console.error('更新咨询申请状态失败', error);
    return null;
  }
};

// 获取咨询申请详情
const getConsultationRequestDetail = async (requestId) => {
  try {
    const result = await consultationRequestCollection.doc(requestId).get();
    return result.data;
  } catch (error) {
    console.error('获取咨询申请详情失败', error);
    return null;
  }
};

//-------------------
// 心理测评相关操作
//-------------------

// 创建心理测评结果
const createEvaluationResult = async (resultData) => {
  try {
    const result = await evaluationResultCollection.add({
      data: {
        ...resultData,
        createTime: db.serverDate(),
        updateTime: db.serverDate()
      }
    });
    return result._id;
  } catch (error) {
    console.error('创建心理测评结果失败', error);
    return null;
  }
};

// 获取学生的所有测评结果
const getStudentEvaluationResults = async (studentId) => {
  try {
    const result = await evaluationResultCollection.where({
      studentId: studentId
    }).orderBy('evaluationTime', 'desc').get();
    return result.data;
  } catch (error) {
    console.error('获取学生测评结果失败', error);
    return [];
  }
};

// 获取老师填写的所有测评结果
const getTeacherEvaluationResults = async (teacherId) => {
  try {
    const result = await evaluationResultCollection.where({
      teacherId: teacherId
    }).orderBy('evaluationTime', 'desc').get();
    return result.data;
  } catch (error) {
    console.error('获取老师测评结果失败', error);
    return [];
  }
};

// 获取测评结果详情
const getEvaluationResultDetail = async (resultId) => {
  try {
    const result = await evaluationResultCollection.doc(resultId).get();
    return result.data;
  } catch (error) {
    console.error('获取测评结果详情失败', error);
    return null;
  }
};

//-------------------
// 班级相关操作
//-------------------

// 创建班级
const createClass = async (classData) => {
  // 不使用classes集合，此处提供一个模拟实现
  console.log('createClass: 不再使用classes集合，请更新相关代码');
  try {
    // 返回成功但不执行实际操作
    return {
      success: true,
      message: '班级数据现在存储在用户集合中，此函数已废弃'
    };
  } catch (error) {
    console.error('创建班级失败', error);
    return null;
  }
};

// 更新班级
const updateClass = async (classId, classData) => {
  // 不使用classes集合，此处提供一个模拟实现
  console.log('updateClass: 不再使用classes集合，请更新相关代码');
  try {
    // 返回成功但不执行实际操作
    return {
      success: true,
      message: '班级数据现在存储在用户集合中，此函数已废弃'
    };
  } catch (error) {
    console.error('更新班级信息失败', error);
    return null;
  }
};

// 获取班级列表
const getClassList = async (counselorId = null) => {
  try {
    // 从users集合中提取班级信息，替代classes集合
    const result = await db.collection('users').field({
      class: true,
      classes: true
    }).get();
    
    // 提取所有班级信息
    const classSet = new Set();
    
    result.data.forEach(user => {
      // 处理单个class字段
      if (user.class) {
        classSet.add(user.class);
      }
      
      // 处理classes数组字段
      if (user.classes && Array.isArray(user.classes)) {
        user.classes.forEach(cls => {
          if (cls) classSet.add(cls);
        });
      }
    });
    
    // 转换为数组并排序
    const classList = Array.from(classSet).sort();
    
    // 格式化为需要的数据结构
    const formattedClassList = classList.map(className => ({
      id: className,
      name: className
    }));
    
    return formattedClassList;
  } catch (error) {
    console.error('获取班级列表失败', error);
    return [];
  }
};

// 获取班级详情
const getClassDetail = async (classId) => {
  try {
    // 从users集合获取指定班级的学生信息
    const result = await db.collection('users').where({
      $or: [
        { class: classId },
        { classes: db.command.all([classId]) }
      ]
    }).get();
    
    // 获取班级学生列表
    const students = result.data.filter(user => user.role === 'student');
    
    // 获取班级辅导员列表
    const teachers = result.data.filter(user => user.role === 'teacher');
    
    return {
      id: classId,
      name: classId,
      students: students,
      teachers: teachers,
      studentCount: students.length
    };
  } catch (error) {
    console.error('获取班级详情失败', error);
    return null;
  }
};

//-------------------
// 心理量表相关操作
//-------------------

// 获取量表列表
const getScaleList = async () => {
  try {
    const result = await psychologicalScaleCollection.orderBy('createTime', 'desc').get();
    return result.data;
  } catch (error) {
    console.error('获取量表列表失败', error);
    return [];
  }
};

// 获取量表详情
const getScaleDetail = async (scaleId) => {
  try {
    const result = await psychologicalScaleCollection.doc(scaleId).get();
    return result.data;
  } catch (error) {
    console.error('获取量表详情失败', error);
    return null;
  }
};

// 创建测试记录
const createTestRecord = async (recordData) => {
  try {
    const result = await psychologicalScaleCollection.add({
      data: {
        ...recordData,
        createTime: db.serverDate(),
        updateTime: db.serverDate()
      }
    });
    return result._id;
  } catch (error) {
    console.error('创建测试记录失败', error);
    return null;
  }
};

//-------------------
// 预约时间段相关操作
//-------------------

// 创建时间段
const createTimeSlot = async (slotData) => {
  try {
    const result = await timeSlotCollection.add({
      data: {
        ...slotData,
        status: 'available',
        currentAppointments: 0,
        createTime: db.serverDate(),
        updateTime: db.serverDate()
      }
    });
    return result._id;
  } catch (error) {
    console.error('创建时间段失败', error);
    return null;
  }
};

// 更新时间段状态
const updateTimeSlotStatus = async (slotId, status, currentAppointments = null) => {
  try {
    const data = {
      status,
      updateTime: db.serverDate()
    };
    if (currentAppointments !== null) {
      data.currentAppointments = currentAppointments;
    }
    const result = await timeSlotCollection.doc(slotId).update({
      data
    });
    return result;
  } catch (error) {
    console.error('更新时间段状态失败', error);
    return null;
  }
};

// 获取可用时间段
const getAvailableTimeSlots = async (date = null) => {
  try {
    let query = timeSlotCollection.where({
      status: 'available'
    });
    if (date) {
      query = query.where({
        date: date
      });
    }
    const result = await query.orderBy('startTime', 'asc').get();
    return result.data;
  } catch (error) {
    console.error('获取可用时间段失败', error);
    return [];
  }
};

//-------------------
// 干预记录相关操作
//-------------------

// 创建干预记录
const createInterventionRecord = async (recordData) => {
  try {
    const result = await interventionRecordCollection.add({
      data: {
        ...recordData,
        createTime: db.serverDate(),
        updateTime: db.serverDate()
      }
    });
    return result._id;
  } catch (error) {
    console.error('创建干预记录失败', error);
    return null;
  }
};

// 更新干预记录
const updateInterventionRecord = async (recordId, recordData) => {
  try {
    const result = await interventionRecordCollection.doc(recordId).update({
      data: {
        ...recordData,
        updateTime: db.serverDate()
      }
    });
    return result;
  } catch (error) {
    console.error('更新干预记录失败', error);
    return null;
  }
};

// 获取干预记录列表
const getInterventionRecords = async (userId = null, operatorId = null) => {
  try {
    let query = interventionRecordCollection;
    if (userId) {
      query = query.where({
        userId: userId
      });
    }
    if (operatorId) {
      query = query.where({
        operatorId: operatorId
      });
    }
    const result = await query.orderBy('createTime', 'desc').get();
    return result.data;
  } catch (error) {
    console.error('获取干预记录列表失败', error);
    return [];
  }
};

// 导出所有数据库操作函数
module.exports = {
  db,
  getUserInfo,
  createUser,
  updateUser,
  userCollection,
  consultationRequestCollection,
  evaluationResultCollection,
  createConsultationRequest,
  getStudentConsultationRequests,
  getPendingConsultationRequests,
  updateConsultationRequestStatus,
  getConsultationRequestDetail,
  createEvaluationResult,
  getStudentEvaluationResults,
  getTeacherEvaluationResults,
  getEvaluationResultDetail,
  // 新增的集合
  classCollection,
  psychologicalScaleCollection,
  timeSlotCollection,
  interventionRecordCollection,
  // 新增的班级操作
  createClass,
  updateClass,
  getClassList,
  getClassDetail,
  // 新增的心理量表操作
  getScaleList,
  getScaleDetail,
  createTestRecord,
  // 新增的预约时间段操作
  createTimeSlot,
  updateTimeSlotStatus,
  getAvailableTimeSlots,
  // 新增的干预记录操作
  createInterventionRecord,
  updateInterventionRecord,
  getInterventionRecords,
  getUserInfoByUsernameAndPassword,
  getUserInfoByUsername
}; 